#!c:/perl/bin/perl.exe

use lib qw(/wwcom/v2.0/cgi-bin);

use DBI;
use DBD::mysql;
use Diva::DB;
use WWCOM;
use CGI;
use strict;
	
my $DEBUG= 1;

my $dbh= Diva::DB->new;

$dbh->set( {
	DATABASE_NAME       => 'wwcom',
	DATABASE_SERVER     => 'localhost:3306',
	DATABASE_USERNAME   => 'wwcom',
	DATABASE_PASSWORD   => 'wwcom',
	DATABASE_TYPE       => 'mysql',
	} );
$dbh->connect();

my $cgi= new CGI;
my %outvars;

my @names= <$WWCOM::NEWSDIR/*.news>;
@names= sort {
	$a=~ /.*\/[0-9]+\.[0-9]+\.([0-9]{2})\-([0-9]{2})\-([0-9]{4})\.([0-9]{2})\-([0-9]{2})\-([0-9]{4})\.*/;
	my $newesta= $6.$5.$4;
	$b=~ /.*\/[0-9]+\.[0-9]+\.([0-9]{2})\-([0-9]{2})\-([0-9]{4})\.([0-9]{2})\-([0-9]{2})\-([0-9]{4})\.*/;
	my $newestb= $6.$5.$4;
	$newesta <=> $newestb;} @names; #sort files by content date

my %allstories;
my $cols= ['STORY_TITLE','STORY_BODY','STORY_AUTHOR','STORY_URL','STORY_SITE','STORY_SITEURL','FK_OBJECT_ID'];
my $vals;

for(my $i= 0; $i<$#names; $i++) {
	print "File: $names[$i]\n";
	my %storyhash= &WWCOM::READFILE($names[$i]);
	$vals= [];
	my $count= 0;
	
	foreach my $key (keys %storyhash) {
		print "\tStory: $key - $storyhash{$key}{'title'}\n";
		$allstories{$key}= $storyhash{$key};
		my $title= $dbh->decode($storyhash{$key}{'title'});
		my $date= $dbh->decode($storyhash{$key}{'date'});
		$date=~ /([0-9]+)\.([\d]+)\.([\d]+)/;
		my $db_date= "$3-$2-$1 12:00:00";
		if ($db_date eq '-- 12:00:00') {
			$db_date= '0000-00-00 12:00:00';
		}
		print "\t** $date: $db_date\n";

		
		my ($sth,$rv)= $dbh->get(['OBJECT','NEWS'],['PK_OBJECT_ID'],'',"FK_OBJECT_ID=PK_OBJECT_ID and NEWS_TITLE=".
			$dbh->handle->quote($title));
			
		if ($rv > 0) {
			my $res= $sth->fetchrow_arrayref;
			$allstories{$key}{PK_OBJECT_ID}= $res->[0];
			print "\t\tFound Object: ".$res->[0].", ObjectID: ".$res->[0]."\n";
#            $dbh->update('OBJECT',['OBJECT_DATE'],[$db_date],"PK_OBJECT_ID=".$res->[0]);
		}
		$sth->finish;        
	}
}
  
# now do relationships    
my $ins_arr= [];
my $ins_arr2= [];
foreach my $key (keys %allstories) {
	if ($allstories{$key}{'relatedthreadtitles'} ne "" && 
			defined $allstories{$key}{PK_OBJECT_ID} && $allstories{$key}{PK_OBJECT_ID} != 0) {
		print "Related: $key - $allstories{$key}{'relatedthreads'}\n";                  
		for (split(/\s+/,$allstories{$key}{'relatedthreads'})) {
			if (defined $allstories{$_}{PK_OBJECT_ID} && $allstories{$_}{PK_OBJECT_ID} != 0) {
				$ins_arr->[$#$ins_arr+1]= [$allstories{$key}{PK_OBJECT_ID}, $allstories{$_}{PK_OBJECT_ID},1,'Manual'];
				$ins_arr2->[$#$ins_arr2+1]= [$allstories{$_}{PK_OBJECT_ID}, $allstories{$key}{PK_OBJECT_ID}, 1,'Manual'];
			}
		}
	}
}
my ($rv)= $dbh->replace('RELATED',['FK_OBJECT_ID','FK_RELATED_ID','FK_CONTENTTYPE_ID','RELATED_TYPE'],$ins_arr);
my ($rv)= $dbh->replace('RELATED',['FK_OBJECT_ID','FK_RELATED_ID','FK_CONTENTTYPE_ID','RELATED_TYPE'],$ins_arr2);



$dbh->disconnect; 